package com.lagou.biz.servlet;

import com.alibaba.druid.support.json.JSONUtils;
import com.lagou.biz.pojo.Result;
import com.lagou.biz.service.AccountService;
import com.lagou.factory.AnnotationConfigApplicationContext;
import com.lagou.utils.PropertyUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * desc:
 *
 * @author tengfei wang
 * @version 1.0
 * @date Created in 8/9/2020
 */
@WebServlet(name = "AccountServlet", urlPatterns = "/transfer")
public class AccountServlet extends HttpServlet {

    private AccountService accountService;

    @Override
    public void init() throws ServletException {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(PropertyUtil.getBasePackage());
        accountService = (AccountService) applicationContext.getBean("accountService");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Result result = new Result();
        try {
            String fromCardNo = request.getParameter("fromCardNo");
            String toCardNo = request.getParameter("toCardNo");
            String money = request.getParameter("money");
            accountService.transferMoney(fromCardNo, toCardNo, Integer.parseInt(money));
            result.setCode(200);
            result.setMessage("success");
        } catch (Exception e) {
            result.setCode(201);
            result.setMessage("transfer exception");
        }

        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(result.toString());
    }
}
